﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FortuneCat.Domain.Abstract;
using FortuneCat.WebUI.Models;
using FortuneCat.Domain.Entities;

namespace FortuneCat.WebUI.Controllers {

    [Authorize]
    public class HomeController : Controller {
        private IBalanceRepository _balanceRepository;
        private IUserRepository _userRepository;

        public int PageSize = 10;
        public int VisiblePages = 10;

        public HomeController(
            IBalanceRepository balanceRepository,
            IUserRepository userRepository) {
            _balanceRepository = balanceRepository;
            _userRepository = userRepository;
        }


        //
        // GET: /Home/

        public ActionResult Index(AccountInfo account) {
            return View(account);
        }


        //
        // 收支表

        public ActionResult List(int page = 1) {
            var model = new BalanceListViewModel() {
                Balances = _balanceRepository.Items
                    .OrderByDescending(x => x.BalanceDate)
                    .ThenByDescending(x => x.EntryTime)
                    .Skip((page - 1) * PageSize)
                    .Take(PageSize).ToList(),
                PagingInfo = new PagingInfo {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = _balanceRepository.Items.Count(),
                    VisiblePages = VisiblePages
                }
            };

            decimal totalBalance = 0m;
            if (_balanceRepository.Items.Count() > 0) {
                totalBalance = _balanceRepository.Items.Sum(x => x.Amount);
            }
            model.TotalBalance = totalBalance;

            decimal totalReceipt = 0m;
            if (_balanceRepository.Items.Count(x => x.Amount > 0) > 0) {
                totalReceipt = _balanceRepository.Items.Where(x => x.Amount > 0).Sum(x => x.Amount);
            }
            model.TotalReceipt = totalReceipt;

            decimal totalPayment = 0m;
            if (_balanceRepository.Items.Count(x => x.Amount < 0) > 0) {
                totalPayment = Math.Abs(_balanceRepository.Items.Where(x => x.Amount < 0).Sum(x => x.Amount));
            }
            model.TotalPayment = totalPayment;

            return PartialView(model);
        }


        //
        // 新增

        public ActionResult Save(AccountInfo account, int id = 0) {
            var model = new SaveBalanceViewModel();

            if (id == 0) {
                model.BalanceDate = DateTime.Now.Date;
            }
            else {
                var balance = (from x in _balanceRepository.Items
                               where x.Id == id
                               select x).FirstOrDefault();
                model.Id = balance.Id;
                model.UserId = balance.UserId;
                model.IsReceipt = balance.Amount > 0m;
                model.Amount = Math.Abs(balance.Amount);
                model.BalanceDate = balance.BalanceDate;
                model.Reason = balance.Reason;
            }

            model.Users = new SelectList(_userRepository.Items.ToList(), "Id", "Nickname", id == 0 ? account.User.Id : model.UserId);

            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Save(AccountInfo account, SaveBalanceViewModel model) {
            if (ModelState.IsValid) {
                Balance balance = null;
                if (model.Id == 0) {
                    balance = new Balance() {
                        Id = 0,
                        EntryTime = DateTime.Now
                    };
                }
                else {
                    balance = (from x in _balanceRepository.Items
                               where x.Id == model.Id
                               select x).FirstOrDefault();
                }

                balance.UserId = model.UserId;
                balance.BalanceDate = model.BalanceDate;
                balance.Amount = model.IsReceipt ? model.Amount : -1 * model.Amount;
                balance.Reason = model.Reason;

                _balanceRepository.Save(balance);

                return Json(new {
                    Success = true
                });
            }

            model.Users = new SelectList(_userRepository.Items.ToList(), "Id", "Nickname", model.UserId);
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Delete(int id) {
            try {
                var balance = (from x in _balanceRepository.Items
                               where x.Id == id
                               select x).FirstOrDefault();
                _balanceRepository.Delete(balance);

                return Json(new {
                    Success = true
                });
            }
            catch (Exception ex) {
                return Json(new {
                    Success = false,
                    Message = ex.Message
                });
            }
        }
    }
}
